package com.tdam2011.grupo02.ui;

import java.util.Date;
import java.util.LinkedList;

import com.tdam2011.grupo02.R;
import com.tdam2011.grupo02.domain.Llamada;
import com.tdam2011.grupo02.data.LogsController;
import com.tdam2011.grupo02.widget.popup.ActionItem;
import com.tdam2011.grupo02.widget.popup.QuickAction;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.CallLog;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.ListFragment;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class CallLogListFragment extends ListFragment implements
		OnClickDialogFragmentInterface {

	private CallBaseAdapter callAdapter;
	private ListView callListView;
	private TextView cantLlamadas;
	private int adapterPosition;
	private QuickAction callPopup;
	private Context context;
	private CallsAsyncTask callsAsyncTask;
	private ViewGroup l;
	private Llamada call;
	private LogsController controller;
	private static final String TAG = "CallLogFragment";

	private final static int POPUP_ACTION_ITEM_CALL = 11;
	private final static int POPUP_ACTION_ITEM_DELETE = 12;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setListShown(true);

		callListView = getListView();

		callAdapter = new CallCustomAdapter();
		callListView.setAdapter(callAdapter);
		callListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long arg3) {
				adapterPosition = position;
				call = (Llamada) callAdapter.getItem(adapterPosition);
				callPopup.show(v);
			}

		});

		createCallPopup();

		controller = new LogsController(context);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		l = (ViewGroup) inflater.inflate(R.layout.log_calls, container);
		cantLlamadas = (TextView) l.findViewById(R.id.txtvCantidadLlamadas);

		return super.onCreateView(inflater, container, savedInstanceState);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = getActivity();
	}

	@Override
	public void onResume() {
		initData();

		super.onResume();
	}

	private void initData() {
		ContactDataInterface data = (ContactDataInterface) context;
		String id = data.onDataSelected()[0];
		String nombreContacto = data.onDataSelected()[1];

		callsAsyncTask = new CallsAsyncTask();
		callsAsyncTask.execute(id, nombreContacto);
	}

	/**
	 * Inicializa el Popup Menu del historial de llamadas, cuando se selecciona
	 * un item de la lista de llamadas
	 */
	public void createCallPopup() {
		ActionItem llamarItem = new ActionItem(POPUP_ACTION_ITEM_CALL,
				getString(R.string.actionCall), getResources().getDrawable(
						android.R.drawable.ic_menu_call));
		ActionItem eliminarItem = new ActionItem(POPUP_ACTION_ITEM_DELETE,
				getString(R.string.actionDelete), getResources().getDrawable(
						android.R.drawable.ic_menu_delete));

		callPopup = new QuickAction(context);

		callPopup.addActionItem(llamarItem);
		callPopup.addActionItem(eliminarItem);

		callPopup
				.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
					@Override
					public void onItemClick(QuickAction quickAction, int pos,
							int actionId) {
						Llamada aux = (Llamada) callAdapter
								.getItem(adapterPosition);

						switch (actionId) {
						case POPUP_ACTION_ITEM_CALL:
							ContactActionControllerSingleton
									.getInstance(context)
									.getContactActionController()
									.makeCall(aux.getNumero());
							break;
						case POPUP_ACTION_ITEM_DELETE:
							showDialog();
							break;
						}

					}
				});

		callPopup.setOnDismissListener(new QuickAction.OnDismissListener() {
			@Override
			public void onDismiss() {
			}
		});
	}

	private class CallsAsyncTask extends
			AsyncTask<String, String, LinkedList<Llamada>> {

		@Override
		protected LinkedList<Llamada> doInBackground(String... params) {
			return controller.getCalls(params[0], params[1]);
		}

		@Override
		protected void onPostExecute(LinkedList<Llamada> result) {
			callAdapter.add(result);
			callAdapter.notifyDataSetChanged();
			Log.d(TAG,
					"onPostExecute() - adapter.getCount() = "
							+ callAdapter.getCount());
			cantLlamadas.setText(callAdapter.getCount() + " ");
			super.onPostExecute(result);
		}
	}

	/**************** CALL ADAPTERS ********************************/

	private class CallBaseAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return 0;
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		public void add(LinkedList<Llamada> llamadas) {
		};

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return null;
		}
	}

	private class CallCustomAdapter extends CallBaseAdapter {
		private LinkedList<Llamada> llamadasLogInfos;
		private LayoutInflater inflater;

		public CallCustomAdapter() {
			llamadasLogInfos = new LinkedList<Llamada>();
			inflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return llamadasLogInfos.size();
		}

		@Override
		public Object getItem(int position) {
			return llamadasLogInfos.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		public void add(LinkedList<Llamada> llamadas) {
			llamadasLogInfos = llamadas;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {
			Holder holder;
			final Llamada info = (Llamada) getItem(position);
			int tipoLlamada;

			if (convertView == null) {
				convertView = inflater.inflate(R.layout.item_llamadaslog, null);
				holder = new Holder();
				((CheckedTextView) convertView
						.findViewById(R.id.chktvLlamadasLogEliminar))
						.setVisibility(View.GONE);
				holder.imgvContacto = (ImageView) convertView
						.findViewById(R.id.imgvContacto);
				holder.txtNombre = (TextView) convertView
						.findViewById(R.id.txtvNombre);
				holder.txtNumero = (TextView) convertView
						.findViewById(R.id.txtvNumero);
				holder.imgTipoLlamada = (ImageView) convertView
						.findViewById(R.id.imgvTipoLlamada);
				holder.txtFecha = (TextView) convertView
						.findViewById(R.id.txtvFecha);
				holder.txtDuracion = (TextView) convertView
						.findViewById(R.id.txtvDuracion);

				convertView.setTag(holder);
			} else {
				holder = (Holder) convertView.getTag();
			}

			switch (info.getTipoLlamada()) {
			case CallLog.Calls.INCOMING_TYPE:
				tipoLlamada = android.R.drawable.sym_call_incoming;
				break;

			case CallLog.Calls.OUTGOING_TYPE:
				tipoLlamada = android.R.drawable.sym_call_outgoing;
				break;

			case CallLog.Calls.MISSED_TYPE:
				tipoLlamada = android.R.drawable.sym_call_missed;
				break;

			default:
				tipoLlamada = android.R.drawable.stat_notify_error;
				break;
			}

			Date date = info.getFecha();
			String timeFormat = DateFormat.getTimeFormat(context).format(date);
			String dateFormat = DateFormat.getDateFormat(context).format(date);

			if (info.getImagen() != null)
				holder.imgvContacto.setImageURI(info.getImagen());
			holder.txtNombre.setText(info.getNombre());
			holder.txtNumero.setText(info.getNumero());
			holder.txtFecha.setText(dateFormat + " - " + timeFormat);
			holder.txtDuracion.setText(info.getDuracion());
			holder.imgTipoLlamada.setBackgroundResource(tipoLlamada);

			return convertView;
		}

		class Holder {
			private ImageView imgvContacto;
			private TextView txtNombre;
			private TextView txtNumero;
			private ImageView imgTipoLlamada;
			private TextView txtFecha;
			private TextView txtDuracion;
		}
	}

	// Dialog Fragment

	private void showDialog() {
		DialogFragment newFragment = MyAlertDialogFragment.newInstance(this,
				getString(R.string.attentionAlertDialogTitle),
				getString(R.string.deleteItemAlertDialogMessage));
		newFragment.show(getFragmentManager(), "dialog");
	}

	@Override
	public void doPositiveClick() {
		int num = controller.deleteCallLogItem(call);
		if (num != 0)
			initData();
	}

	@Override
	public void doNegativeClick() {
	}
}
